import { connect } from "react-redux";
import request from "../utils/request";
import React from "react";
import { Redirect } from "react-router-dom";

// 使用属性代理方式实现用户访问权限控制
export function withLogin(InnerComponent) {
  function OuterComponent(props) {
    // 判断用户是否登录
    if (props.userinfo.authorization) {
      // 校验token有效性（是否过期，是否被篡改）
      request.get("/users/verify").then(({ data }) => {
        if (data.code === 0) {
          props.history.push({
            pathname: "/login",
            search: "targetUrl=" + props.location.pathname,
          });
        }
      });
      return <InnerComponent {...props}></InnerComponent>;
    } else {
      return <Redirect to="/login" />;
    }
  }

  OuterComponent = connect(
    (state) => {
      return {
        userinfo: state.userinfo.userinfo,
      };
    },
    () => {
      return {};
    }
  )(OuterComponent);

  return OuterComponent;
}
